<?php

namespace common\base;

use yii\base\InvalidArgumentException;

/**
 * FormModel is the base class for data form models.
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
abstract class FormModel extends Model {
    
    /**
     * @var integer 主键ID值
     */
    public $id = 0;
    
    /**
     * @var \common\db\ActiveRecord 数据原型模型
     */
    protected $modelClass;
    
    /**
     * @var \yii\db\ActiveRecordInterface 启动模型
     */
    private $_model = null;
    
    /**
     * 初始化基类
     *
     * @param integer $id
     * @param array $config
     * @inheritdoc
     */
    public function __construct($id = 0, $config = []) {
        $this->setModel($id);
        parent::__construct($config);
    }
    
    /**
     * 获取基础模型
     *
     * @return \yii\db\ActiveRecordInterface|null {$this->modelClass}::className()
     */
    public function getModel() {
        return $this->_model;
    }
    
    /**
     * 初始化基础模型
     *
     * @throws \yii\web\NotFoundHttpException
     */
    public function setModel($id) {
        $modelClass = $this->modelClass;
        if ($id) {
            $model = $modelClass::findOrFail($id);
            $this->setAttributes($model->attributes, false);
        } else {
            $model = new $modelClass();
        }
        if ($model == null) {
            throw new InvalidArgumentException('Undefind Model');
        }
        $this->setExtraAttributes($model);
        $this->_model = $model;
    }
    
    /**
     * 关联模型属性设置
     *
     * @param Object $model 模型对象
     */
    abstract public function setExtraAttributes($model);
    
    /**
     * 是否新增记录
     *
     * @return boolean
     */
    public function getIsNewRecord() {
        if ($this->id) {
            return false;
        }
        return true;
    }
    
}
